import com.alibaba.fastjson.JSON;
import com.aliyun.odps.udf.UDF;
import com.aliyun.odps.utils.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 解析药监局检验方法
 * 
 * @author asus
 *
 */
public class SpliderProductInspectionMethods extends UDF {

	
	/*
	 * public static void main(String[] args) { String html = TestHtml.html();
	 * evaluate(html,"aaa"); }
	 */

	public List<String> evaluate(String html, String goodsId) {
		List<String> list = new ArrayList<String>();
		try {
			// 判空
			if (StringUtils.isNotBlank(html)) {
				Document document = Jsoup.parse(html);
				// html是传过来的检验方法的这个标签 所以直接获取对应的检验方法的下一行
				Elements eles = document.select("tr:contains(检验方法)+tr");
				if (null != eles) {
					Elements elementsByBody = eles.get(0).getElementsByTag("tbody");
					if (null != elementsByBody && elementsByBody.size() == 1) {
						// 获取对应的tr标签
                        Elements elementsByTr = elementsByBody.get(0).getElementsByTag("tr");
                        String tableName = null;
						for (int i = 1; i < elementsByTr.size(); i++) {
							Map<String, Object> obj = new HashMap<String, Object>();
							// 从第二行开始遍历 因为第一行是检验项目、检验方法的title
							Elements elementsByTd = elementsByTr.get(i).getElementsByTag("td");
							// 判断td的size 如果是3 则带了表名 如果是2则说明就是检验的项目名称和检验方法的名称
							if (elementsByTd.size() == 3) {
								// 获取表名
								tableName = elementsByTd.get(0).text();
								String inspectionItems = elementsByTd.get(1).text();
								String inspectionMethods = elementsByTd.get(2).text();
								obj.put("goodsId", goodsId);// 产品id
								obj.put("inspectionItems", inspectionItems);// 检验的项目
								obj.put("inspectionMethods", inspectionMethods);// 检验方法
								obj.put("tableName", tableName);// 表名
								list.add(JSON.toJSONString(obj));
							} else if (elementsByTd.size() == 2) {
								String inspectionItems = elementsByTd.get(0).text();
								String inspectionMethods = elementsByTd.get(1).text();
								obj.put("goodsId", goodsId);// 产品id
								obj.put("inspectionItems", inspectionItems);// 检验的项目
								obj.put("inspectionMethods", inspectionMethods);// 检验方法
								obj.put("tableName", tableName);// 表名
								list.add(JSON.toJSONString(obj));
							}
						}

					}
				}
			}else if(StringUtils.isNotBlank(goodsId)) {
				Map<String, Object> obj = new HashMap<String, Object>();
				obj.put("goodsId", goodsId);
				list.add(JSON.toJSONString(obj));
			}

			System.out.println(JSON.toJSONString(list));
			return list;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			Map<String, Object> obj = new HashMap<String, Object>();
			obj.put("e", e.getMessage());
			list.add(JSON.toJSONString(obj));
			return list;
		}
	}

}
